package cn.javaxc.mvcwork.util.common;
import java.io.*;
import java.util.prefs.Preferences;
import javax.servlet.ServletContext;




public class PrefUtils {

//  public static String retrieveContextPrefName(ServletContext context) {
//    String dir = MVCConfig.getRealPath(context);
//    try {
//      // Some containers return null so use the specified instance
//      if (dir == null) {
//        dir = loadText(context, "/WEB-INF/instance.property");
//      }
//      // Apache Geronimo without a plan file uses a temporary store for a webapp
//      // which would prevent a redeployed/upgraded Centric from finding itself
//      if (dir != null && dir.indexOf("config-store") > -1) {
//        dir = loadText(context, "/WEB-INF/instance.property");
//      }
//      // Apache Geronimo with a plan file and a module artifactId can use the
//      // artifactId to differentiate
//      if (dir != null && dir.indexOf("repository/default") > -1) {
//        int uniqueIdStart = dir.indexOf("repository/default") + 19;
//        dir = dir.substring(uniqueIdStart, dir.indexOf("/", uniqueIdStart));
//      }
//      System.err.println("Prefs-> Instance name: " + dir);
//    } catch (Exception e) {
//      e.printStackTrace(System.out);
//    }
//    return dir;
//  }

  
  public static String loadText(ServletContext context, String filename) throws IOException {
    InputStream in = context.getResourceAsStream(filename);
    StringBuffer text = new StringBuffer();
    byte b[] = new byte[1];
    while (in.read(b) != -1) {
      text.append(new String(b));
    }
    in.close();
    return text.toString();
  }
  
  public static boolean savePref(String name, String value) {
    try {
      Preferences prefs = Preferences.userNodeForPackage(cn.javaxc.mvcwork.controller.Prefs.class);
      if (name.length() <= Preferences.MAX_KEY_LENGTH) {
        prefs.put(name, value);
      } else {
        prefs.put(name.substring(name.length() - Preferences.MAX_KEY_LENGTH), value);
      }
      prefs.flush();
      return true;
    } catch (Exception e) {
      e.printStackTrace(System.out);
      return false;
    }
  }
}
